package cn.topcodes.tcsf.admin.web.controller.impl;

import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.service.licence.LicenceException;
import cn.topcodes.tcsf.admin.service.licence.LicenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author Unicorn
 * @date 2017/5/10
 */
@Controller
@RequestMapping("/licence")
public class LicenceController {

    @Autowired
    private LicenceService licenceService;

    /*系统注册页面*/
    @RequestMapping(value = "",method = RequestMethod.GET)
    public String index(Model model) {
        try {
            licenceService.validate();
            return "/";
        }catch(LicenceException e) {
            model.addAttribute("machineCode",licenceService.getMatchineCode());
            return "admin/licence/licence";
        }
    }

    /*系统注册*/
    @ResponseBody
    @RequestMapping(value = "register",method = RequestMethod.POST)
    public ApiResponseEntity register(@RequestParam(required = true) String code) {
        try {
            licenceService.validate();
            return ApiResponseEntity.buildFailed("系统已授权");
        }catch(LicenceException e) {
            try {
                this.licenceService.register(code);
                return ApiResponseEntity.buildOK();
            } catch (LicenceException e1) {
                return ApiResponseEntity.buildFailed(e1.getMessage());
            }

        }
    }
}
